<template>
  <a-tabs v-model:active-key="activeKey">
    <a-tab-pane key="1" title="基础设置">
      <div class="basic-setting">
        <div class="common-text">{{ props.desc }}</div>
        <div class="mt10">
          <a-space>
            <div>是否开启接单：</div>
            <div>
              <a-switch v-model="form.enabled">
                <template #checked> 开 </template>
                <template #unchecked> 关 </template>
              </a-switch>
            </div>
            <div class="common-text">只有开启接单才能接该类型任务单，否则无法接单。</div>
          </a-space>
        </div>
        <div class="mt10">
          <a-space>
            <div>是否开启内审：</div>
            <div>
              <a-switch v-model="form.enabledCheck">
                <template #checked> 开 </template>
                <template #unchecked> 关 </template>
              </a-switch>
            </div>
            <div class="common-text">开启之后，任务先进入到内审再提交验收</div>
          </a-space>
        </div>
        <div class="mt10">
          <a-space>
            <div class="required">每日可交付数：</div>
            <div style="width: 400px">
              <a-input v-model="form.maxDeliveryNumPerday" placeholder="请输入最大可接单数" />
            </div>
          </a-space>
        </div>
        <div style="width: 520px; text-align: center; margin-top: 30px">
          <a-button class="gray-outline" @click="reset">重置</a-button>
          <a-button class="ml10" type="primary" :loading="submitLoading" @click="submit">保存</a-button>
        </div>
      </div>
    </a-tab-pane>
    <a-tab-pane key="2" title="服务项目">
      <div class="service-item">
        <a-scrollbar style="height: calc(100vh - 150px); overflow: auto">
          <div class="clearfix">
            <div class="item fl mr10 mb10" v-for="(item, index) of serviceList" :key="index">
              <div class="top clearfix">
                <div class="fl ser-Content">
                  <div class="fl ser-Content">
                    <TextLimit :val="item.serContent" :rows="1" position="top"></TextLimit>
                  </div>
                </div>
                <div class="fr common-text">ID:{{ item.serShortId }}</div>
              </div>

              <div class="mt5">
                <span class="common-text">交付内容：</span>
                <span>{{ deliveryData(item.taskNodeList) }}</span>
              </div>
              <div class="mt5">
                <span class="common-text">执行周期：</span>
                <span>{{ item.executeCycle }}天</span>
              </div>
              <div class="mt5">
                <span class="common-text">报价：</span>
                <span
                  ><span style="color: red; font-size: 14px">￥{{ item.amtQuote }}</span
                  >/单</span
                >
              </div>
              <div class="clearfix footer">
                <div class="fl" style="width: 130px">
                  <a-switch v-model="item.enabled" @change="changeStatus($event, item)">
                    <template #checked> 开 </template>
                    <template #unchecked> 关 </template>
                  </a-switch>
                </div>
                <div class="fr">
                  <a-button size="mini" shape="round" class="gray-outline" @click="del(item.id)">删除</a-button>
                  <a-button class="ml10" size="mini" shape="round" type="primary" @click="show('edit', item)">编辑</a-button>
                </div>
              </div>
            </div>
            <div class="item fl mr10 mb10 item-add cursor" @click="show('add')">
              <div style="text-align: center">
                <div>
                  <icon-plus class="common-text" style="font-size: 30px" />
                </div>
                <div class="common-text" style="font-size: 16px"> 新增服务项目 </div>
              </div>
            </div>
          </div>
        </a-scrollbar>
      </div>
    </a-tab-pane>
  </a-tabs>

  <serviceItemdetail :taskType="props.taskType" v-if="showModal" :configId="updateConfigInfo.id" v-model="showModal" :type="type" :info="info" @save="getConfig" />
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { nodeMap, deliveryMap, originPicSourceMap } from './map'
  import { saveOrUpdateTaskConfig, getTaskConfigByTaskType, delTaskService, updateTaskServiceEnable } from '@/api/task'
  import serviceItemdetail from './serviceItemdetail.vue'
  import _ from 'lodash-es'

  const props = defineProps(['taskType', 'desc'])
  let activeKey = ref('1')
  let type = ref('add')
  let info: any = ref({})
  let showModal = ref(false)
  let submitLoading = ref(false)
  let updateConfigInfo: any = ref({})
  let serviceList: any = ref([])
  let form: any = ref({
    enabled: false,
    enabledCheck: false,
    maxDeliveryNumPerday: '',
    sampleAddress: {
      userName: '',
      phone: '',
      stateOrRegion: '',
      city: '',
      address: '',
    },
  })

  const reset = () => {
    form.value = {
      id: form.value.id || '',
      enabled: form.value.id ? updateConfigInfo.value.enabled : false,
      enabledCheck: form.value.id ? updateConfigInfo.value.enabledCheck : false,
      maxDeliveryNumPerday: form.value.id ? updateConfigInfo.value.maxDeliveryNumPerday : '',
      sampleAddress: {
        userName: form.value.id ? updateConfigInfo.value.sampleAddress.userName : '',
        phone: form.value.id ? updateConfigInfo.value.sampleAddress.phone : '',
        stateOrRegion: form.value.id ? updateConfigInfo.value.sampleAddress.stateOrRegion : '',
        city: form.value.id ? updateConfigInfo.value.sampleAddress.city : '',
        address: form.value.id ? updateConfigInfo.value.sampleAddress.address : '',
      },
    }
  }

  const show = (addType: string, data?: any) => {
    type.value = addType
    info.value = data || {}
    showModal.value = true
  }

  const submit = async () => {
    if (!form.value.maxDeliveryNumPerday) {
      return Message.error('请输入最大可接单数')
    }

    let params = {
      taskType: props.taskType,
      ...form.value,
    }

    try {
      submitLoading.value = true
      const res: any = await saveOrUpdateTaskConfig(params)
      if (res) {
        Message.success('配置更新成功')
        getConfig()
      }
    } catch (error) {}
    submitLoading.value = false
  }

  const getConfig = async () => {
    let res: any = await getTaskConfigByTaskType({ taskType: props.taskType })
    if (res) {
      updateConfigInfo.value = _.cloneDeep(res.data) || {}
      form.value.id = res.data?.id || ''
      form.value.enabled = res.data?.enabled || false
      form.value.enabledCheck = res.data?.enabledCheck || false
      form.value.maxDeliveryNumPerday = res.data?.maxDeliveryNumPerday || ''
      form.value.sampleAddress = res.data?.sampleAddress || {}
      serviceList.value = res.data?.taskServiceList || []
    }
  }

  const deliveryData = (list: any) => {
    let arr = list.reduce((pre: any, cur: any) => {
      return (pre = [...pre, ...cur.taskContentList])
    }, [])
    return arr
      .filter((ell: any) => ell.quantity && ell.quantity > 0)
      .map((e: any) => `${deliveryMap[e.contentType]}×${e.quantity}`)
      .join(',')
  }

  const del = (id: string) => {
    Modal.error({
      title: '删除服务',
      content: '请再次确认是否需要删除',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        let params = {
          configId: updateConfigInfo.value.id,
          taskServiceId: id,
        }
        const res: any = await delTaskService(params)
        if (res.code == 'SUCCESS') {
          Message.success('删除成功')
          getConfig()
        }
      },
    })
  }

  const changeStatus = async (val: boolean, data: any) => {
    let params = {
      configId: updateConfigInfo.value.id,
      enabled: val,
      taskServiceId: data.id,
    }
    const res: any = await updateTaskServiceEnable(params)
    if (res) {
      Message.success('状态更新成功')
      // getConfig()
    }
  }

  onMounted(() => {
    getConfig()
  })
</script>

<style lang="less" scoped>
  .mt5 {
    margin-top: 5px;
  }

  .common-text {
    font-size: 12px;
    color: #a39999;
  }

  .basic-setting {
    padding: 5px;
  }

  .service-item {
    padding: 5px 0 5px 5px;
    .item {
      width: 250px;
      height: 200px;
      border: 1px solid #e5e6eb;
      border-radius: 5px;
      padding: 5px;
      font-size: 12px;
      position: relative;
      .footer {
        position: absolute;
        bottom: 10px;
      }
    }

    .item-add {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
</style>
